var BUCKET_CURRENT = 'v1'

self.addEventListener('install', function(event) {
  console.log('[EVENT_INSTALL]')
  event.waitUntil(
    caches.open(BUCKET_CURRENT).then(self.skipWaiting)
  );
});

console.log('update oh shit ok yes -6')

self.addEventListener('fetch', function(event) {
  console.log(
    '\n================\n',
    '[EVENT_FETCH]: ', event,
    '[EVENT_FETCH_REQUEST]: ', event.request,
    '\n================\n',
  )

  event.respondWith(
    caches.match(event.request).then(function(resp) {
      // console.log('[REQUEST]:', event.request)
      return resp || fetch(event.request).then(function(response) {
        console.log('[EVENT_FETCH] lose cache', response)
        var shouldCache = response.ok;
        if (event.request.method == 'POST') { shouldCache = false }

        var respToCache = response.clone();
        shouldCache && caches.open(BUCKET_CURRENT).then(function(cache) {
          cache.put(event.request, respToCache);
        });

        return response
      });
    }).catch(function(e){
      console.log('[EVENT_FETCH] fetch error', e)
    })
  );
});

self.addEventListener('activate', function(event) {
  console.log('[EVENT_ACTIVATE]')
  var cacheWhitelist = [];

  event.waitUntil(
    caches.keys().then(function(keyList) {
      // console.log('[CACHES_KEYS]', keyList)
      return Promise.all(keyList.map(function(key) {
        if (cacheWhitelist.indexOf(key) === -1) {
          return caches.delete(key);
        }
      }));
    })
  );
});